const express = require("express");
const app = express();
const path = require("path");
const log4js = require("log4js");
const bodyParser=require("body-parser");


//设置绝对路径
const resolvepath = {
  root_path: path.resolve(__dirname, "../public"),
  src_path: path.resolve(__dirname, "../../src"),
};

//设置http请求的中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended:true
}))

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "POST,GET");
  res.header("X-Powered-By", " 3.2.1");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

app.use("/home", (req, res, next) => {
  let getClientIp =  (req)=> {
    return (
      req.headers["x-forwarded-for"] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.connection.socket.remoteAddress ||
      ""
    );
  };
  let ip=getClientIp(req).match(/\d+.\d+.\d+.\d+/);
  logger.publicinfo("有用户登录首页了,ip为",ip);
  next();
});

//当token失效返回提示信息 时间过期了执行这一条
app.use((err, req, res, next) => {
  if (err.status === 401) {
    return res.json({
      status: err.status,
      msg: 'token失效',
      error: err.name + ':' + err.message
    })
  }
});

//捕获uncaughtException 防止程序意外关闭
process.on('uncaughtException', function (err) {
  //打印出错误
  console.log(err);
  //打印出错误的调用栈方便调试
  console.log(err.stack)
});

//日志信息
log4js.configure({
  appenders: {
    error: { type: "file", filename: "./log/error.log", compress: true },
    info: { type: "file", filename: "./log/info.log", compress: true },
    debug: { type: "file", filename: "./log/debug.log", compress: true },
  },
  categories: {
    default: { appenders: ["error"], level: "error" },
    error: { appenders: ["error"], level: "error" },
    info: { appenders: ["info"], level: "info" },
    debug: { appenders: ["debug"], level: "debug" },
  },
});
let logger = {
  publicerror: (errormessage, error) => {
    log4js.getLogger("error").error(`${errormessage}:${error}`);
  },
  publicinfo: (infomessage, info) => {
    log4js.getLogger("info").info(`${infomessage}:${info}`);
  },
  publicdebug: (debugmessage, debug) => {
    log4js.getLogger("debug").debug(`${debugmessage}:${debug}`);
  },
};

module.exports = {
  app,
  resolvepath,
  logger,
};
